package com.dld.coupon.activity;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Element;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SearchScrollView;
import android.widget.TextView;

import com.constant.net.Constant;
import com.dld.android.net.HttpUtil;
import com.dld.android.net.Param;
import com.dld.android.persistent.SharePersistent;
import com.dld.android.util.LogUtils;
import com.dld.android.view.DragViewGroup;
import com.dld.android.view.OnTouchListenerImpl;
import com.dld.coupon.util.Common;
import com.dld.coupon.util.FileUtil;
import com.dld.coupon.util.MD5Encoder;
import com.dld.coupon.util.MapUtil;
import com.dld.coupon.util.StringUtils;
import com.dld.coupon.util.MapUtil.LatAndLon;
import com.dld.coupon.util.MapUtil.LocationObserver;
import com.dld.coupon.view.UMSearchBar;
import com.dld.protocol.ProtocolHelper;
import com.dld.protocol.image.ImageProtocol;
import com.dld.protocol.json.CProtocol;
import com.dld.protocol.json.HuoDongResponse;
import com.dld.protocol.json.Promotion;
import com.dld.protocol.json.Protocol;
import com.json.entity.AdImageBean;
import com.json.entity.RecmmCouponBean;

public class SearchActivity extends BaseActivity implements LocationObserver {
	public static final String[] ADS;
	static final CategoryImage[] CATEGORIES;
	private final int GETHUODONGURLSUCCESS = 5;
	private static String cityId;
	private DragViewGroup activities;
	private int activityCount = 0;
	private DragViewGroup ads;
	private String cityName;
	private ProgressDialog pd;

	Handler handler = new Handler() {
		public void handleMessage(Message paramMessage) {
			switch (paramMessage.what) {
			case 5:
			}
		}
	};
	View.OnClickListener onClose = new View.OnClickListener() {
		public void onClick(View paramView) {
			SearchActivity.this.activities.setVisibility(8);
		}
	};
	private List<Promotion> proList;
	private SearchScrollView scroll;
	private UMSearchBar searchBar;
	private boolean showing = false;
	private Timer timer = new Timer();

	static {
		Object[] localObject = new String[4];
		localObject[0] = "http://www.dld.com/KC/WAP/mdl/mdl.html";
		localObject[1] = "http://www.dld.com/KC/WAP/yonghe/yh.html";
		localObject[2] = "http://www.dld.com/KC/WAP/zgf/zgf.html";
		localObject[3] = "http://www.dld.com/KC/WAP/hhg/hhg.html";
		ADS = (String[]) localObject;
		localObject = new CategoryImage[8];

		localObject[0] = new CategoryImage(R.drawable.cat_1, "美食", 101);
		localObject[1] = new CategoryImage(R.drawable.cat_2, "购物", 102);
		localObject[2] = new CategoryImage(R.drawable.cat_3, "休闲", 103);
		localObject[3] = new CategoryImage(R.drawable.cat_4, "住宿", 104);
		localObject[4] = new CategoryImage(R.drawable.cat_5, "交通", 105);
		localObject[5] = new CategoryImage(R.drawable.cat_6, "旅游", 106);
		localObject[6] = new CategoryImage(R.drawable.cat_7, "运动", 107);
		localObject[7] = new CategoryImage(R.drawable.cat_8, "便民", 108);
		CATEGORIES = (CategoryImage[]) localObject;
	}

	private void waitDialog(String message) {
		pd = ProgressDialog.show(this, "", message, false);
		pd.show();
	}

	private void downloadCoupon() {
		cityId = SharePersistent.getInstance().getPerference(this, "city_id");
		Param pram = new Param();
		pram.append("r", "www/api/list");
		pram.append("userAgent", "dld_android");
		pram.append("module", "discountRecommend");
		pram.append("areaCode", cityId);

		Protocol p = new Protocol(pram);
		p.startTrans(new Protocol.OnJsonProtocolResult(String.class) {
			@Override
			public void onException(String paramString, Exception paramException) {

				SearchActivity.this.handler.post(new Runnable() {
					public void run() {
						TextView tv = (TextView) findViewById(R.id.text_net_info);
						tv.setText("网络异常加载失败,请检查网络... ");
					}
				});
			}

			@Override
			public void onResult(String paramString, Object paramObject) {
				String content = (String) paramObject;
				try {
					Element root = DocumentBuilderFactory
							.newInstance()
							.newDocumentBuilder()
							.parse(new ByteArrayInputStream(content.getBytes()))
							.getDocumentElement();
					final List<RecmmCouponBean> list = RecmmCouponBean
							.fromXmlToAdroundInfo(root);
					runOnUiThread(new Runnable() {

						public void run() {
							initHotRange(list);
						}

					});

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void init() {
		this.cityName = SharePersistent.getInstance().getPerference(this,
				"city_name");
		this.searchBar = ((UMSearchBar) findViewById(R.id.search_bar));
		this.searchBar.setOnSearchListener(new UMSearchBar.OnSearchListener() {
			public void onSearch(int paramInt, String paramString) {
				Intent localIntent = new Intent();
				localIntent.setClass(SearchActivity.this,
						SearchResultActivity.class);
				localIntent.putExtra("keyword", paramString);
				localIntent.putExtra("type", SearchActivity.this.searchBar
						.getPosition());
				SearchActivity.this.startActivity(localIntent);
			}
		});
		initActivities();
		initCategory();
		CityActivity.registObserver(new CityActivity.NotifyChangeObserver() {
			public void onChangeCity(String paramString1, String paramString2) {
				SearchActivity.this.cityName = paramString1;
				SearchActivity.this.downloadCoupon();
				
				initAdsNetWork();
				try {
					((TextView) SearchActivity.this
							.findViewById(R.id.title_text)).setText("首页-"
							+ SearchActivity.this.cityName);
				} catch (Exception localException) {
					LogUtils.e("test", "", localException);
				}
			}
		});

		// initActivities();

		((TextView) findViewById(R.id.title_text)).setText("首页-" + "城市");
		((Button) findViewById(R.id.switchcity_top_btn))
				.setOnClickListener(new View.OnClickListener() {
					public void onClick(View paramView) {
						Common.startActivity(CityActivity.class);
					}
				});

		Handler mapHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Log.v("citychange", "*******8*************8   ");
			}
		};
		MapUtil.regist(this, mapHandler, this);
		waitDialog("定位过程中，请稍等...");

	}

	private void initActivities() {
		this.activityCount = 0;
		this.activities = ((DragViewGroup) findViewById(R.id.activities));
		this.scroll.setTopChild(this.activities);
	}

	private void initCategory() {
		LinearLayout localLinearLayout3 = (LinearLayout) findViewById(R.id.categories);
		LayoutInflater localLayoutInflater = (LayoutInflater) getSystemService("layout_inflater");
		int j = (int) (0.98D * (ActivityManager.getCurrent().getWindowManager()
				.getDefaultDisplay().getWidth() / 4));
		int m = 0;
		int k = CATEGORIES.length / 4;
		while (m < k) {
			LinearLayout localLinearLayout2 = (LinearLayout) localLayoutInflater
					.inflate(R.layout.search_linear, null);
			for (int i = 0; i < 4; i++) {
				CategoryImage localCategoryImage = CATEGORIES[(i + m * 4)];
				LinearLayout localLinearLayout1 = (LinearLayout) localLayoutInflater
						.inflate(R.layout.search_category, null);
				((ImageView) localLinearLayout1.findViewById(R.id.image))
						.setImageResource(localCategoryImage.imageId);
				((TextView) localLinearLayout1.findViewById(R.id.text))
						.setText(localCategoryImage.text);
				setCategory(localLinearLayout1, localCategoryImage);
				localLinearLayout2.addView(localLinearLayout1,
						new LinearLayout.LayoutParams(j, j));
			}
			localLinearLayout3.addView(localLinearLayout2);
			m++;
		}
	}

	private void bindData(ImageView img, String url) {
		ImageProtocol pl = new ImageProtocol(this, url);
		pl.startTrans(img);
	}

	private void initAdsNetWork() {
		Param param = new Param();
		param.append("r", "www/api/list");
		param.append("userAgent", "dld_android");
		param.append("module", "homead");
		param.append("areaCode", MapUtil.getCityId());
		Protocol prot = new Protocol(param);
		prot.startTrans(new Protocol.OnJsonProtocolResult(String.class) {

			@Override
			public void onException(String paramString, Exception paramException) {
				Log.v("", "********     " + paramException.toString());
			}

			@Override
			public void onResult(String paramString, Object paramObject) {
				String content = (String) paramObject;
				try {
					Element root = DocumentBuilderFactory
							.newInstance()
							.newDocumentBuilder()
							.parse(new ByteArrayInputStream(content.getBytes()))
							.getDocumentElement();
					final List<AdImageBean> list = AdImageBean
							.fromXmlToAdroundInfo(root);
					runOnUiThread(new Runnable() {

						public void run() {

							LayoutInflater inflater = LayoutInflater
									.from(SearchActivity.this);
							OnClickListener click = new OnClickListener() {
								public void onClick(View v) {
									String shopid = (String) v.getTag();
									Intent it = new Intent(v.getContext(),
											StoreDetail.class);
									it.putExtra(Constant.CONSTANT_SHOPID,
											shopid);
									startActivity(it);
								}
							};
							SearchActivity.this.ads.removeAllViews();
							for (int i = 0; i < list.size(); i++) {
								View child = inflater.inflate(
										R.layout.scroll_item, null);
								ImageView img = (ImageView) child
										.findViewById(R.id.activity_1);
								bindData(img, list.get(i).getLogo());
								img.setTag(list.get(i).getLink());
								img.setOnClickListener(click);
								SearchActivity.this.ads.addView(child);
							}
						}

					});

				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});
	}

	private void initHotRange(List<RecmmCouponBean> localList) {

		LinearLayout localLinearLayout = (LinearLayout) findViewById(R.id.hot_addresses);
		if (localList.size() < 0 || localList.isEmpty()) {
			TextView tv = (TextView) findViewById(R.id.text_net_info);
			findViewById(R.id.no_result).setVisibility(View.VISIBLE);
			tv.setText("暂时没有可以查看的内容");
			localLinearLayout.removeAllViews();
			return;
		}
		LayoutInflater localLayoutInflater = (LayoutInflater) getSystemService("layout_inflater");
		localLinearLayout.removeAllViews();

		View.OnClickListener listener = new View.OnClickListener() {
			public void onClick(View v) {
				RecmmCouponBean tag = (RecmmCouponBean) v.getTag();
				Intent it = new Intent(SearchActivity.this, StoreDetail.class);
				it.putExtra(Constant.CONSTANT_SHOPID, tag.getShopid());
				SearchActivity.this.startActivity(it);
			}
		};
		if (!localList.isEmpty()) {
			findViewById(R.id.no_result).setVisibility(View.GONE);
			for (int i = 0; i < 3 && i < localList.size(); i++) {
				View localView = localLayoutInflater.inflate(
						R.layout.search_hot_address, null);
				localView.setBackgroundResource(R.drawable.listitem_selected);
				TextView tv = (TextView) localView.findViewById(R.id.text_left);
				TextView indicator = (TextView) localView
						.findViewById(R.id.indicator);
				int orderNo = i + 1;
				indicator.setText("" + orderNo);
				tv.setText(localList.get(i).getTitle());
				localView.setOnClickListener(listener);
				localView.setTag(localList.get(i));
				localLinearLayout.addView(localView);
			}
		} else {
			findViewById(R.id.no_result).setVisibility(View.VISIBLE);
		}
	}

	private void initMyActivity(final String paramString1,
			final String paramString2) {
		LogUtils.log("test", paramString1);
		final View localView = ((LayoutInflater) getSystemService("layout_inflater"))
				.inflate(R.layout.activity_img, null).findViewById(
						R.id.activity);
		localView.setOnClickListener(new View.OnClickListener() {
			public void onClick(View paramView) {
				SearchActivity.this.forward(paramString1, false);
			}
		});
		localView.findViewById(R.id.close).setOnClickListener(this.onClose);
		new Thread() {
			public void run() {
				try {
					Object localObject = FileUtil
							.getByteFromInputStream(HttpUtil
									.getInputStreamByUrl(paramString2,
											SearchActivity.this));
					FileUtil.writehuodongCache(new ByteArrayInputStream(
							(byte[]) localObject), MD5Encoder
							.toHexString(paramString2.getBytes()));
					final Bitmap bitmap = FileUtil
							.getBitmapFromInputStream(new ByteArrayInputStream(
									(byte[]) localObject));
					if (localObject != null)
						SearchActivity.this.handler.post(new Runnable() {
							public void run() {
								Object localObject1 = new BitmapDrawable(
										SearchActivity.this.getResources(),
										(Bitmap) bitmap);
								localView
										.setBackgroundDrawable((Drawable) localObject1);
								SearchActivity.this.activities.setVisibility(0);
								SearchActivity.this.activities
										.addView(localView);
								localObject1 = SearchActivity.this;
								((SearchActivity) localObject1).activityCount = (1 + ((SearchActivity) localObject1).activityCount);
							}
						});
					return;
				} catch (Exception localException) {
					while (true)
						LogUtils.e("test", localException);
				}
			}
		}.start();
	}

	private void initTimer() {
		this.timer.schedule(new TimerTask() {
			public void run() {
				if (SearchActivity.this.showing)
					SearchActivity.this.handler.post(new Runnable() {
						public void run() {
							long l = System.currentTimeMillis();
							if ((SearchActivity.this.ads.rest())
									&& (l
											- SearchActivity.this.ads
													.getLastSnapped() >= 8000L)) {
								int j = SearchActivity.this.ads.getFocusIndex();
								if (j < 1)
									SearchActivity.this.ads.snapToScreen(j + 1);
								else
									SearchActivity.this.ads.reset();
							}
							if ((SearchActivity.this.activityCount > 0)
									&& (SearchActivity.this.activities.rest())
									&& (l
											- SearchActivity.this.activities
													.getLastSnapped() >= 8000L)) {
								int i = SearchActivity.this.activities
										.getFocusIndex();
								if (i < -1 + SearchActivity.this.activityCount)
									SearchActivity.this.activities
											.snapToScreen(i + 1);
								else
									SearchActivity.this.activities.reset();
							}
						}
					});
			}
		}, 10000L, 10000L);
	}

	private void setCategory(View paramView,
			final CategoryImage paramCategoryImage) {
		paramView.setOnClickListener(new View.OnClickListener() {
			public void onClick(View paramView) {
				Activity localActivity = ActivityManager.getCurrent();
				int i = SearchActivity.this.searchBar.getPosition();
				Intent localIntent = new Intent();
				Object localObject;
				if (paramCategoryImage.value != 0)
					localObject = CategoryActivity.class;
				else
					localObject = SearchResultActivity.class;
				localIntent.setClass(localActivity, (Class) localObject);
				localIntent.putExtra("type", i);
				localIntent.putExtra("cat", paramCategoryImage.value);
				localIntent.putExtra("cat_name", paramCategoryImage.text);
				localActivity.startActivity(localIntent);
			}
		});
		paramView.setOnTouchListener(new OnTouchListenerImpl(paramView,
				R.drawable.category_selected));
	}

	public void forward(String paramString, boolean paramBoolean) {
		Intent localIntent = new Intent();
		localIntent.setClass(this, Browsers.class);
		localIntent.putExtra("url", paramString);
		localIntent.putExtra("backable", paramBoolean);
		startActivity(localIntent);
	}

	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.search_view);
		this.showing = true;
		this.scroll = ((SearchScrollView) findViewById(R.id.scroll));
		this.ads = ((DragViewGroup) findViewById(R.id.ads));
		this.scroll.setBottomChild(this.ads);
		init();
		initTimer();
		this.handler.postDelayed(new Runnable() {
			public void run() {
				if (pd.isShowing()) {
					showCityChooseDialog(null);
				}
			}
		}, 1000 * 15);

	}

	protected void onDestroy() {
		super.onDestroy();
		this.showing = false;
		this.timer.cancel();
		this.timer = null;
	}

	public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {
		return false;
	}

	protected void onPause() {
		super.onPause();
		this.showing = false;
	}

	protected void onResume() {
		super.onResume();
		this.showing = true;
	}

	static final class CategoryImage {
		int imageId;
		String text;
		int value;

		public CategoryImage(int paramInt1, String paramString, int paramInt2) {
			this.imageId = paramInt1;
			this.text = paramString;
			this.value = paramInt2;
		}
	}

	private void showCityChooseDialog(String current) {
		pd.dismiss();
		AlertDialog.Builder adb = new AlertDialog.Builder(this);
		final AlertDialog ad = adb.create();
		current = "定位失败，请重新选择城市";
		ad.setTitle("定位信息");
		ad.setMessage(current);
		ad.setButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Intent it = new Intent(SearchActivity.this, CityActivity.class);
				startActivity(it);
			}
		});
		ad.setButton2("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				ad.dismiss();
			}
		});
		ad.show();

	}

	public void onFailed() {

		Log.v("", "handler *************  onfailed   ");
		pd.dismiss();
		showCityChooseDialog(null);

	}

	public void onLocationChanged(LatAndLon paramLatAndLon) {

	}

	public void onCityChanged(final String currentCity) {
		pd.dismiss();
		downloadCoupon();
		initActivities();
		initAdsNetWork();

		if (currentCity != null) {
			handler.post(new Runnable() {
				public void run() {
					((TextView) findViewById(R.id.title_text)).setText("首页-"
							+ currentCity);
				}
			});

		}
	}
}
